using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace KisloidTools.Logger
{
    public sealed class Logger
    {
        private string _logFileName;

        private XmlWriter _xmlWriter;

        private XmlWriterSettings _xmlWriterSettings;

        private bool _started = false;

        public Logger(string logFileName)
        {
            _logFileName = logFileName;

            _xmlWriterSettings = new XmlWriterSettings();
            _xmlWriterSettings.Indent = true;
        }

        public void Start()
        {
            _started = true;

            _xmlWriter = XmlWriter.Create(_logFileName, _xmlWriterSettings);

            _xmlWriter.WriteStartElement("Root");

            _xmlWriter.WriteStartElement("LogMessage");
            _xmlWriter.WriteAttributeString("Date", GetCurrentDate());
            _xmlWriter.WriteAttributeString("Time", GetCurrentTime());
            _xmlWriter.WriteValue("Start logging");
            _xmlWriter.WriteEndElement();
        }

        public void Stop()
        {
            _xmlWriter.WriteStartElement("LogMessage");
            _xmlWriter.WriteAttributeString("Date", GetCurrentDate());
            _xmlWriter.WriteAttributeString("Time", GetCurrentTime());
            _xmlWriter.WriteValue("Stop logging");
            _xmlWriter.WriteEndElement();

            // root element
            _xmlWriter.WriteEndElement();

            _xmlWriter.Flush();
            _xmlWriter.Close();

            _started = false;
        }

        public void Write(string message)
        {
            _xmlWriter.WriteStartElement("LogMessage");
            _xmlWriter.WriteAttributeString("Date", GetCurrentDate());
            _xmlWriter.WriteAttributeString("Time", GetCurrentTime());
            _xmlWriter.WriteValue(message);
            _xmlWriter.WriteEndElement();
        }

        private string GetCurrentDate()
        {
            string result =
                DateTime.Now.ToShortDateString();

            return result;
        }

        private string GetCurrentTime()
        {
            string result =
                DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" +
                DateTime.Now.Second + "'" + DateTime.Now.Millisecond;

            return result;
        }

        public bool Started
        {
            get
            {
                return _started;
            }
        }
    }
}
